<template>
  <div class="ewe-history-container">
    <!-- 简化操作栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd" size="default">
        <el-icon><Plus /></el-icon>
        新增记录
      </el-button>
      <el-button type="success" @click="handleRefresh" size="default">
        <el-icon><RefreshLeft /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table :data="tableData" border style="width: 100%" empty-text="暂无数据" stripe :loading="loadingTable">
        <el-table-column prop="historyId" label="历史ID" width="80" align="center" />
        <el-table-column prop="eweId" label="种母耳号" align="center" min-width="120" />
        <el-table-column prop="matingDate" label="配种日期" align="center" min-width="120" :formatter="(row: any) => formatDate(row.matingDate)" />
        <el-table-column prop="ramId" label="种公耳号" align="center" min-width="120" />
      <el-table-column prop="pregnancyCheckDate" label="妊检日期" align="center" min-width="120" :formatter="(row: any) => formatDate(row.pregnancyCheckDate)" />
      <el-table-column prop="pregnancyResult" label="妊检结果" align="center" min-width="100" />
      <el-table-column prop="deliveryDate" label="分娩日期" align="center" min-width="120" :formatter="(row: any) => formatDate(row.deliveryDate)" />
      <el-table-column prop="healthyLambCount" label="健羔数" align="center" min-width="80" />
      <el-table-column prop="healthyLambTotalWeight" label="健羔总重" align="center" min-width="100" />
      <el-table-column prop="weakLambCount" label="弱羔数" align="center" min-width="80" />
      <el-table-column prop="deformedCount" label="畸形数" align="center" min-width="80" />
      <el-table-column prop="stillbirthCount" label="死胎数" align="center" min-width="80" />
      <el-table-column prop="mummyCount" label="木乃伊数" align="center" min-width="80" />
      <el-table-column prop="abnormalCount" label="畸胎数" align="center" min-width="80" />
      <el-table-column prop="currentParity" label="当前胎次" align="center" min-width="80" />
      <el-table-column prop="note" label="备注" align="center" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{ row }">
              <div class="operation-buttons">
                <el-button type="primary" link @click="handleView(row)">
                  <el-icon><View /></el-icon>查看
                </el-button>
                <el-button type="warning" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </div>
            </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 简化底部统计 -->
    <div class="footer-section">
      <div class="stats-summary">
        <span class="stats-item">总健羔: <strong>{{ totalHealthyLambs }}</strong></span>
        <span class="stats-item">总弱羔: <strong>{{ totalWeakLambs }}</strong></span>
        <span class="stats-item">总畸形: <strong>{{ totalDeformedLambs }}</strong></span>
        <span class="stats-item">总死胎: <strong>{{ totalStillbirths }}</strong></span>
        <span class="stats-item">总木乃伊: <strong>{{ totalMummies }}</strong></span>
        <span class="stats-item">总畸形: <strong>{{ totalMalformed }}</strong></span>
        <span class="stats-item">总记录: <strong>{{ tableData.length }}</strong></span>
      </div>
    </div>

    <!-- 简化对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
        label-position="right"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="种母耳号" prop="EweId">
              <el-select
                v-model="formData.EweId"
                placeholder="请选择耳号"
                size="default"
                clearable
                filterable
                :loading="loadingEweEarTags"
                style="width: 100%"
                :disabled="dialogType === 'view'"
              >
                <el-option
                  v-for="option in eweEarTagOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="种公耳号" prop="RamId">
              <el-select
                v-model="formData.RamId"
                placeholder="请选择耳号"
                size="default"
                clearable
                filterable
                :loading="loadingRamEarTags"
                style="width: 100%"
                :disabled="dialogType === 'view'"
              >
                <el-option
                  v-for="option in ramEarTagOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配种日期" prop="MatingDate">
              <el-date-picker
                v-model="formData.MatingDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="dialogType === 'view'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="妊检日期" prop="PregnancyCheckDate">
              <el-date-picker
                v-model="formData.PregnancyCheckDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="dialogType === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="妊检结果" prop="PregnancyResult">
              <el-input
                v-model="formData.PregnancyResult"
                placeholder="请输入"
                :disabled="dialogType === 'view'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分娩日期" prop="DeliveryDate">
              <el-date-picker
                v-model="formData.DeliveryDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="dialogType === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 产羔信息 -->
        <el-divider content-position="left">产羔信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="健羔数" prop="HealthyLambCount">
              <el-input-number
                v-model="formData.HealthyLambCount"
                :min="0"
                :precision="0"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="健羔总重" prop="HealthyLambTotalWeight">
              <el-input-number
                v-model="formData.HealthyLambTotalWeight"
                :min="0"
                :precision="2"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="弱羔数" prop="WeakLambCount">
              <el-input-number
                v-model="formData.WeakLambCount"
                :min="0"
                :precision="0"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="畸形数" prop="DeformedCount">
              <el-input-number
                v-model="formData.DeformedCount"
                :min="0"
                :precision="0"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="死胎数" prop="StillbirthCount">
              <el-input-number
                v-model="formData.StillbirthCount"
                :min="0"
                :precision="0"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="木乃伊数" prop="MummyCount">
              <el-input-number
                v-model="formData.MummyCount"
                :min="0"
                :precision="0"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="畸胎数" prop="AbnormalCount">
              <el-input-number
                v-model="formData.AbnormalCount"
                :min="0"
                :precision="0"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前胎次" prop="CurrentParity">
              <el-input-number
                v-model="formData.CurrentParity"
                :min="1"
                :precision="0"
                :disabled="dialogType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="Note">
              <el-input
                v-model="formData.Note"
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
                :disabled="dialogType === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="handleSubmit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus, Document, RefreshLeft, Delete, Minus, View, Edit } from '@element-plus/icons-vue'
import { Writes, Reads } from '@/Utils/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

// 表格数据（后端字段映射版）
const tableData = ref([
  {
    HistoryId: 0,
    EweId: 0,
    MatingDate: '',
    RamId: null as number | null,
    PregnancyCheckDate: '',
    PregnancyResult: '',
    DeliveryDate: '',
    HealthyLambCount: 0,
    HealthyLambTotalWeight: 0,
    WeakLambCount: 0,
    DeformedCount: 0,
    StillbirthCount: 0,
    MummyCount: 0,
    AbnormalCount: 0,
    CurrentParity: 0,
    Note: ''
  }
])

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 耳号选项列表
const eweEarTagOptions = ref<Array<{value: string, label: string}>>([])
const ramEarTagOptions = ref<Array<{value: string, label: string}>>([])
const loadingEweEarTags = ref(false)
const loadingRamEarTags = ref(false)
const loadingTable = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref<'add' | 'view' | 'edit'>('add')
const formRef = ref<FormInstance>()

// 表单数据（后端字段映射版）
const formData = ref({
  HistoryId: 0,
  EweId: null as number | null,
  MatingDate: '',
  RamId: null as number | null,
  PregnancyCheckDate: '',
  PregnancyResult: '',
  DeliveryDate: '',
  HealthyLambCount: 0,
  HealthyLambTotalWeight: 0,
  WeakLambCount: 0,
  DeformedCount: 0,
  StillbirthCount: 0,
  MummyCount: 0,
  AbnormalCount: 0,
  CurrentParity: 0,
  Note: ''
})

// 表单验证规则（后端字段映射版）
const formRules = {
  EweId: [{ required: true, message: '请选择种母耳号', trigger: 'change' }],
  MatingDate: [{ required: true, message: '请选择配种日期', trigger: 'change' }],
  RamId: [{ required: false, message: '请选择种公耳号', trigger: 'change' }],
  PregnancyCheckDate: [{ required: false, message: '请选择妊检日期', trigger: 'change' }],
  PregnancyResult: [{ required: false, message: '请输入妊检结果', trigger: 'blur' }],
  DeliveryDate: [{ required: false, message: '请选择分娩日期', trigger: 'change' }],
  HealthyLambCount: [{ required: false, message: '请输入健羔数', trigger: 'blur' }],
  HealthyLambTotalWeight: [{ required: false, message: '请输入健羔总重', trigger: 'blur' }],
  WeakLambCount: [{ required: false, message: '请输入弱羔数', trigger: 'blur' }],
  DeformedCount: [{ required: false, message: '请输入畸形数', trigger: 'blur' }],
  StillbirthCount: [{ required: false, message: '请输入死胎数', trigger: 'blur' }],
  MummyCount: [{ required: false, message: '请输入木乃伊数', trigger: 'blur' }],
  AbnormalCount: [{ required: false, message: '请输入畸胎数', trigger: 'blur' }],
  CurrentParity: [{ required: true, message: '请输入当前胎次', trigger: 'blur' }],
  Note: [{ required: false, message: '请输入备注', trigger: 'blur' }]
}

// 计算总健羔数（后端字段映射版）
const totalHealthyLambs = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (row.HealthyLambCount || 0)
  }, 0)
})

// 计算总弱羔数（后端字段映射版）
const totalWeakLambs = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (row.WeakLambCount || 0)
  }, 0)
})

// 计算总畸形数（后端字段映射版）
const totalDeformedLambs = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (row.DeformedCount || 0)
  }, 0)
})

// 计算总死胎数（后端字段映射版）
const totalStillbirths = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (row.StillbirthCount || 0)
  }, 0)
})

// 计算总木乃伊数（后端字段映射版）
const totalMummies = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (row.MummyCount || 0)
  }, 0)
})

// 计算总畸胎数（后端字段映射版）
const totalMalformed = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (row.AbnormalCount || 0)
  }, 0)
})

// 增加行（后端字段映射版）
const handleAddRow = () => {
  const newRow = {
    HistoryId: 0,
    EweId: 0,
    MatingDate: '',
    RamId: 0,
    PregnancyCheckDate: '',
    PregnancyResult: '',
    DeliveryDate: '',
    HealthyLambCount: 0,
    HealthyLambTotalWeight: 0,
    WeakLambCount: 0,
    DeformedCount: 0,
    StillbirthCount: 0,
    MummyCount: 0,
    AbnormalCount: 0,
    CurrentParity: 0,
    Note: ''
  }
  tableData.value.push(newRow)
}

// 删除行（后端字段映射版）
const handleDeleteRow = () => {
  if (tableData.value.length > 1) {
    tableData.value.pop()
  } else {
    tableData.value[0] = {
      HistoryId: 0,
      EweId: 0,
      MatingDate: '',
      RamId: 0,
      PregnancyCheckDate: '',
      PregnancyResult: '',
      DeliveryDate: '',
      HealthyLambCount: 0,
      HealthyLambTotalWeight: 0,
      WeakLambCount: 0,
      DeformedCount: 0,
      StillbirthCount: 0,
      MummyCount: 0,
      AbnormalCount: 0,
      CurrentParity: 0,
      Note: ''
    }
  }
}

// 新增记录（后端字段映射版）
const handleAdd = () => {
  dialogTitle.value = '新增历史记录'
  dialogType.value = 'add'
  formData.value = {
    HistoryId: 0,
    EweId: null,
    MatingDate: '',
    RamId: null,
    PregnancyCheckDate: '',
    PregnancyResult: '',
    DeliveryDate: '',
    HealthyLambCount: 0,
    HealthyLambTotalWeight: 0,
    WeakLambCount: 0,
    DeformedCount: 0,
    StillbirthCount: 0,
    MummyCount: 0,
    AbnormalCount: 0,
    CurrentParity: 0,
    Note: ''
  }
  dialogVisible.value = true
}

// 保存数据（后端字段映射版）
const handleSave = async () => {
  try {
    // 验证必填字段
    const hasInvalidData = tableData.value.some(row => {
      return row.EweId === null || row.EweId === undefined || !row.MatingDate || row.CurrentParity === null || row.CurrentParity === undefined
    })

    if (hasInvalidData) {
      ElMessage.warning('请填写完整必填字段（种母耳号、配种日期、当前胎次）')
      return
    }

    // 构建提交数据（完全匹配后端字段）
    const submitData = tableData.value.map(row => ({
      HistoryId: row.HistoryId,
      EweId: row.EweId,
      MatingDate: row.MatingDate,
      RamId: row.RamId,
      PregnancyCheckDate: row.PregnancyCheckDate,
      PregnancyResult: row.PregnancyResult,
      DeliveryDate: row.DeliveryDate,
      HealthyLambCount: row.HealthyLambCount,
      HealthyLambTotalWeight: row.HealthyLambTotalWeight,
      WeakLambCount: row.WeakLambCount,
      DeformedCount: row.DeformedCount,
      StillbirthCount: row.StillbirthCount,
      MummyCount: row.MummyCount,
      AbnormalCount: row.AbnormalCount,
      CurrentParity: row.CurrentParity,
      Note: row.Note
    }))

    console.log('提交数据:', submitData)
    // TODO: 调用后端API保存数据
    ElMessage.success('保存成功！')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 查看
const handleView = (row: any) => {
  dialogTitle.value = '查看历史记录'
  dialogType.value = 'view'
  fillFormData(row)
  dialogVisible.value = true
}

// 编辑（后端字段映射版）
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑历史记录'
  dialogType.value = 'edit'
  formData.value = {
    HistoryId: row.historyId || 0,
    EweId: row.eweId || null,
    MatingDate: row.matingDate || '',
    RamId: row.ramId || null,
    PregnancyCheckDate: row.pregnancyCheckDate || '',
    PregnancyResult: row.pregnancyResult || '',
    DeliveryDate: row.deliveryDate || '',
    HealthyLambCount: Number(row.healthyLambCount) || 0,
    HealthyLambTotalWeight: Number(row.healthyLambTotalWeight) || 0,
    WeakLambCount: Number(row.weakLambCount) || 0,
    DeformedCount: Number(row.deformedCount) || 0,
    StillbirthCount: Number(row.stillbirthCount) || 0,
    MummyCount: Number(row.mummyCount) || 0,
    AbnormalCount: Number(row.abnormalCount) || 0,
    CurrentParity: Number(row.currentParity) || 0,
    Note: row.note || ''
  }
  dialogVisible.value = true
}



// 重置表单（后端字段映射版）
const resetForm = () => {
  formData.value = {
    HistoryId: 0,
    EweId: null,
    MatingDate: '',
    RamId: null,
    PregnancyCheckDate: '',
    PregnancyResult: '',
    DeliveryDate: '',
    HealthyLambCount: 0,
    HealthyLambTotalWeight: 0,
    WeakLambCount: 0,
    DeformedCount: 0,
    StillbirthCount: 0,
    MummyCount: 0,
    AbnormalCount: 0,
    CurrentParity: 0,
    Note: ''
  }
}

// 填充表单数据（后端字段映射版）
const fillFormData = (row: any) => {
  formData.value = {
    HistoryId: row.historyId || 0,
    EweId: row.eweId || null,
    MatingDate: row.matingDate || '',
    RamId: row.ramId || null,
    PregnancyCheckDate: row.pregnancyCheckDate || '',
    PregnancyResult: row.pregnancyResult || '',
    DeliveryDate: row.deliveryDate || '',
    HealthyLambCount: Number(row.healthyLambCount) || 0,
    HealthyLambTotalWeight: Number(row.healthyLambTotalWeight) || 0,
    WeakLambCount: Number(row.weakLambCount) || 0,
    DeformedCount: Number(row.deformedCount) || 0,
    StillbirthCount: Number(row.stillbirthCount) || 0,
    MummyCount: Number(row.mummyCount) || 0,
    AbnormalCount: Number(row.abnormalCount) || 0,
    CurrentParity: Number(row.currentParity) || 0,
    Note: row.note || ''
  }
}

// 提交表单（后端字段映射版）
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 验证必填字段
    if (formData.value.EweId === null || formData.value.EweId === undefined || !formData.value.MatingDate || formData.value.CurrentParity === null || formData.value.CurrentParity === undefined) {
      ElMessage.warning('请填写完整必填字段（种母耳号、配种日期、当前胎次）')
      return
    }

    // 构造提交数据（完全匹配后端字段）
    const submitData = {
      HistoryId: formData.value.HistoryId,
      EweId: Number(formData.value.EweId),
      MatingDate: formData.value.MatingDate,
      RamId: formData.value.RamId ? Number(formData.value.RamId) : null,
      PregnancyCheckDate: formData.value.PregnancyCheckDate,
      PregnancyResult: formData.value.PregnancyResult,
      DeliveryDate: formData.value.DeliveryDate,
      HealthyLambCount: Number(formData.value.HealthyLambCount),
      HealthyLambTotalWeight: Number(formData.value.HealthyLambTotalWeight),
      WeakLambCount: Number(formData.value.WeakLambCount),
      DeformedCount: Number(formData.value.DeformedCount),
      StillbirthCount: Number(formData.value.StillbirthCount),
      MummyCount: Number(formData.value.MummyCount),
      AbnormalCount: Number(formData.value.AbnormalCount),
      CurrentParity: Number(formData.value.CurrentParity),
      Note: formData.value.Note
    }
    
    console.log('提交数据:', submitData)

    if (dialogType.value === 'edit') {
      // 更新现有记录 - 调用后端API
      try {
        const response = await Writes.put('/Management/UpdateEweHistoryRecord', submitData);
        console.log('更新响应:', response)
        
        // 根据响应结果显示消息
         if (response.data && response.data.code === 300) {
           // 成功后重新获取表格数据
           await fetchTableData()
           ElMessage.success('更新成功！')
         } else {
           // 显示后端返回的错误消息
           ElMessage.error('更新失败，请重试')
           return // 不关闭对话框
         }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败，请检查网络连接')
        return // 不关闭对话框
      }
    } else {
      // 新增记录
      const response = await Writes.post('/Management/CreateEweHistoryRecord', submitData);
      console.log('新增响应:', response)
      
      // 根据响应结果显示消息
        if (response.data && response.data.code === 100) {
          // 成功后重新获取表格数据
          await fetchTableData()
          ElMessage.success('新增成功！')
        } else {
          // 显示后端返回的错误消息
          ElMessage.error('新增失败，请重试')
          return // 不关闭对话框
        }
    }

    handleDialogClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查输入数据')
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  formData.value = {
    HistoryId: 0,
    EweId: null,
    MatingDate: '',
    RamId: null,
    PregnancyCheckDate: '',
    PregnancyResult: '',
    DeliveryDate: '',
    HealthyLambCount: 0,
    HealthyLambTotalWeight: 0,
    WeakLambCount: 0,
    DeformedCount: 0,
    StillbirthCount: 0,
    MummyCount: 0,
    AbnormalCount: 0,
    CurrentParity: 0,
    Note: ''
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  fetchTableData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
  fetchTableData()
}

// 获取表格数据（分页）
const fetchTableData = async () => {
  try {
    loadingTable.value = true
    const params = {
      PageIndex: pagination.value.currentPage, // 转换为从0开始的索引
      PageSize: pagination.value.pageSize
    }
    
    console.log('请求参数:', params)
    const response = await Reads.get('/Management/GetEweHistoryRecords', { params })
    console.log('获取历史记录响应:', response)
    
    if (response.data && response.data.code === 400) {
      const data = response.data.data
      if (data && data.data) {
        tableData.value = data.data
        pagination.value.total = data.totalCount || data.data.length
      } else {
        tableData.value = []
        pagination.value.total = 0
      }
    } else {
      ElMessage.error('获取数据失败')
      tableData.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
    tableData.value = []
  } finally {
    loadingTable.value = false
  }
}

// 删除记录（后端字段映射版）
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条历史记录吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用后端API删除记录
    const response = await Writes.delete('/Management/DeleteEweHistoryRecord', {
      data: { historyId: row.historyId }
    });
    console.log('删除请求参数:', { historyId: row.historyId })
    
    console.log('删除响应:', response)
    
    // 根据响应结果显示消息
    if (response.data && response.data.code === 200) {
      // 成功后重新获取表格数据
      await fetchTableData()
      ElMessage.success('删除成功！')
    } else {
      // 显示后端返回的错误消息
      ElMessage.error('删除失败，请重试')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

// 处理刷新按钮点击事件
const handleRefresh = async () => {
  await fetchTableData()
  ElMessage.success('数据已刷新')
}

// 格式化日期时间
const formatDate = (dateString: string | null | undefined) => {
  if (!dateString) return '--'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (error) {
    return dateString
  }
}

// 获取种母耳号列表
const fetchEweEarTagOptions = async () => {
  try {
    loadingEweEarTags.value = true
    const response = await Reads.get('/Management/GetEweFileMenu')
    
    if (response.data && response.data.code === 400) {
      console.log('种母耳号响应数据:', response.data)
      const data = response.data.data || []
      eweEarTagOptions.value = data
    }
  } catch (error) {
    console.error('获取种母耳号列表失败:', error)
  } finally {
    loadingEweEarTags.value = false
  }
}

// 获取种公耳号列表
const fetchRamEarTagOptions = async () => {
  try {
    loadingRamEarTags.value = true
    const response = await Reads.get('/Management/GetRamFileMenu')
    
    if (response.data && response.data.code === 400) {
      console.log('种公耳号响应数据:', response.data)
      const data = response.data.data || []
      ramEarTagOptions.value = data
    }
  } catch (error) {
    console.error('获取种公耳号列表失败:', error)
  } finally {
    loadingRamEarTags.value = false
  }
}

// 处理种母耳号选择事件
const handleEweEarTagSelect = async (value: string | null, row: any) => {
  // 表格中选择事件处理
  console.log('种母耳号选择:', value, row)
}

// 处理种公耳号选择事件
const handleRamEarTagSelect = async (value: string | null, row: any) => {
  // 表格中选择事件处理
  console.log('种公耳号选择:', value, row)
}

// 组件挂载时获取耳号列表和表格数据
onMounted(() => {
  fetchEweEarTagOptions()
  fetchRamEarTagOptions()
  fetchTableData()
})
</script>

<style scoped>
.ewe-history-container {
  padding: 16px;
  background: #ffffff;
  min-height: 100vh;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.table-section {
  background: #ffffff;
  border-radius: 6px;
  overflow: hidden;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  border-radius: 6px;
}

:deep(.el-table th) {
  background-color: #fafafa !important;
  color: #333333 !important;
  font-weight: 500 !important;
  padding: 12px 8px !important;
  border-bottom: 1px solid #f0f0f0 !important;
}

:deep(.el-table td) {
  padding: 10px 8px !important;
  border-bottom: 1px solid #f5f5f5 !important;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa !important;
}

/* 操作按钮样式 */
:deep(.el-button--link) {
  padding: 4px 8px !important;
  font-size: 13px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
  padding: 12px 0;
}

/* 底部统计样式 */
.footer-section {
  margin-top: 16px;
  padding: 12px 16px;
  background: #fafafa;
  border-radius: 6px;
  display: flex;
  justify-content: center;
}

.stats-summary {
  display: flex;
  gap: 24px;
  align-items: center;
}

.stats-item {
  font-size: 14px;
  color: #666;
}

.stats-item strong {
  color: #333;
  font-weight: 600;
  margin-left: 4px;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 16px 20px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-divider__text) {
  background-color: #ffffff;
  color: #666;
  font-size: 13px;
  padding: 0 12px;
}

/* 输入框样式优化 */
:deep(.el-input__wrapper) {
  border-radius: 4px;
  box-shadow: none;
  border: 1px solid #dcdfe6;
}

:deep(.el-input__wrapper):hover {
  border-color: #c0c4cc;
}

:deep(.el-input__wrapper).is-focus {
  border-color: #409eff;
}

/* 数字输入框样式 */
:deep(.el-input-number) {
  width: 100%;
}

/* 日期选择器样式 */
:deep(.el-date-editor) {
  width: 100% !important;
}
</style>

